package models;

import java.lang.reflect.Type;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;

import play.db.jpa.Model;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

@Entity
public class Menu extends Model {
	@ManyToOne(optional=false)
	private Establishment establishment;
	
	@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
	@JoinColumn(name="menu_id")
	@OrderBy("name")
	private Set<MenuSection> sections;

	@OneToOne(cascade=CascadeType.ALL)
	private Picture picture;

	public Establishment getEstablishment() {
		return establishment;
	}

	public void setEstablishment(Establishment establishment) {
		this.establishment = establishment;
	}

	public Set<MenuSection> getSections() {
		return sections;
	}

	public void setSections(Set<MenuSection> sections) {
		this.sections = sections;
	}
	
	public Picture getPicture() {
		return picture;
	}

	public void setPicture(Picture picture) {
		this.picture = picture;
	}

	public static class MenuJsonSerializer implements JsonSerializer<Menu> {
		@Override
		public JsonElement serialize(Menu menu, Type type,
				JsonSerializationContext context) {
			JsonObject menuJson = new JsonObject();
			
			menuJson.addProperty("id", menu.getId());
			
			JsonArray menuSectionsJson =  new JsonArray();
			
			for (MenuSection section : menu.getSections()) {
				JsonObject sectionJson = new JsonObject();
				
				sectionJson.addProperty("id", section.getId());
				sectionJson.addProperty("name", section.getName());
				
				JsonArray itemsJson = new JsonArray();
				
				for (MenuItem item : section.getItems()) {
					JsonObject itemJson = new JsonObject();
					
					itemJson.addProperty("id", item.getId());
					itemJson.addProperty("name", item.getName());
					itemJson.addProperty("price", item.getId());
					
					itemsJson.add(itemJson);
				}
				
				sectionJson.add("items", itemsJson);
			}
			
			menuJson.add("sections", menuSectionsJson);
			
			return menuJson;
		}
	}
}
